package com.mentalhealthplatform.teacherV2.service;

import com.mentalhealthplatform.appModels.Teacher;
import com.mentalhealthplatform.teacherV2.repository.TeacherRepositoryV2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class TeacherServiceV2 {

    @Autowired
    private TeacherRepositoryV2 teacherRepositoryV2;
    @Autowired
    private PasswordEncoder passwordEncoder;

    // 获取所有教师信息
    public List<Teacher> findAll() {
        return teacherRepositoryV2.findAll();
    }

    // 根据ID获取教师信息
    public Teacher getTeacherById(UUID id) {
        return teacherRepositoryV2.findById(id).orElse(null);
    }

    // 根据用户名获取教师信息
    public Teacher findByUsername(String username) {
        Teacher byUsername = teacherRepositoryV2.findByUsername(username);
        return byUsername;
    }

    // 保存教师信息
    public Teacher saveTeacher(Teacher teacher) {
        System.out.println("Saving teacher with phone: " + teacher.getPhone());
        return teacherRepositoryV2.save(teacher);
    }

    // 更新教师密码
    public boolean updatePassword(UUID id, String oldPassword, String newPassword) {
        Teacher teacher = teacherRepositoryV2.findById(id).orElse(null);
        if (teacher == null) {
            return false;
        }

        // 验证旧密码是否正确
        if (!passwordEncoder.matches(oldPassword, teacher.getPassword())) {
            return false;
        }

        // 设置新密码并保存
        teacher.setPassword(passwordEncoder.encode(newPassword));
        teacherRepositoryV2.save(teacher);
        return true;
    }
}